package com.wn34.goods.controller;

import com.wn34.goods.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@RequestMapping("user")
@Controller
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public String login(String username, String password, HttpServletRequest req) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                subject.login(token);
            } catch (UnknownAccountException e) {
                req.setAttribute("errInfo", e.getMessage());
                return "login";
            } catch (IncorrectCredentialsException e) {
                req.setAttribute("errInfo", "密码错误!");
                return "login";
            } catch (LockedAccountException e) {
                req.setAttribute("errInfo", "账户被锁定!");
                return "login";
            } catch (AuthenticationException e) {
                req.setAttribute("errInfo", "未知错误!");
                return "login";
            }
        }
        return "redirect:/goods/goodsList";
    }
}
